package com.example.dqdq.lzyim_asm_tvapp;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.dqdq.lzyim_asm_tvapp.api.API;
import com.example.dqdq.lzyim_asm_tvapp.https.HttpManger;
import com.example.dqdq.lzyim_asm_tvapp.utils.ActivityCollector;
import com.example.dqdq.lzyim_asm_tvapp.utils.FileDownLoad;
import com.testin.agent.TestinAgent;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.x;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.OutputStream;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

public class MainActivity extends BaseActivity {

    private ImageView img;
    private SharedPreferences preferences;
    private SharedPreferences.Editor editor;
    private OutputStream os;
    private Timer timer;
    private int recLen = 4;
    private String FileName = "tvAppLoadImg.jpg";
    private String imgPath="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

//        JPushInterface.setDebugMode(true);
        TestinAgent.init(this, "c6e8248b16fdd66b94712e3df1cbd0f1", "asm");

        JPushInterface.init(this);
        ActivityCollector.addActivity(this);
        preferences = getSharedPreferences("user", Context.MODE_PRIVATE);
        if (preferences.getBoolean("firststart", true)) {
            editor = preferences.edit();
            editor.putBoolean("firststart", true);
            editor.commit();

            Intent intent = new Intent(MainActivity.this, UserGuideActivity.class);
            startActivity(intent);
            finish();
        } else {

            setContentView(R.layout.activity_main);
//            displayImg();
//
            Log.e("test",preferences.getString("random",""));
            JPushInterface.setAlias(MainActivity.this, preferences.getString("random",""), new TagAliasCallback() {
                @Override
                public void gotResult(int i, String s, Set<String> set) {
                    Log.e("setAlias", String.valueOf(i));
                    return;
                };
            });
            checkUpdate(MainActivity.this);
            initView();

        }
    }
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    private void checkUpdate(final Context context) {
        x.http().post(HttpManger.getParams(API.APK_UPDATE_URL, "", ""), new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
                try {
                    PackageManager manager = context.getPackageManager();
                    PackageInfo info = null;
                    Log.e("test", result);
                    info = manager.getPackageInfo(context.getPackageName(), 0);
                    int version = info.versionCode;
                    JSONObject object = new JSONObject(result);
                     final JSONObject data=object.getJSONObject("data");
                    Log.e("version",String.valueOf(data.getInt("versioncode")));
                    if (version < data.getInt("versioncode")) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    FileDownLoad fileDownLoad=new FileDownLoad();
                                    String path= null;
                                    path = fileDownLoad.downLoadApk(API.SERVERC_URL+data.getString("download"),context);
                                    Intent i = new Intent(Intent.ACTION_VIEW);
                                    i.setDataAndType(Uri.parse("file://" + path), "application/vnd.android.package-archive");
                                    context.startActivity(i);
//                                    initView();
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                            }
                        }).start();
                    }
                    else
                    {
                        initView();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    private void initView() {
        timer = new Timer();
        timer.schedule(task, 1000, 1000);       // timeTask
    }

    TimerTask task = new TimerTask(){
        @Override
        public void run() {
            runOnUiThread(new Runnable() {      // UI thread
                @Override
                public void run() {
                    if (recLen == 0) {
                        Intent intent = new Intent(MainActivity.this, WarrantyCardActivity.class);
                        startActivity(intent);
                        timer.cancel();
                        finish();
                    }
                    recLen--;
                }
            });
        }
    };
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        ActivityCollector.removeActivity(this);
    }


    private void displayImg()
    {
        String path = "file";
        String SDCard = Environment.getExternalStorageDirectory() + "";
        imgPath = SDCard + "/" + path + "/" + FileName;//文件存储路径

        File file=new File(imgPath);
        Log.e("test path",imgPath);
        if (file.exists()) {
            img = (ImageView) findViewById(R.id.img);
            Bitmap bitmap = getLoacalBitmap(imgPath); //从本地取图片(在cdcard中获取)  //
            img.setImageBitmap(bitmap); //设置Bitmap
            Log.e("test","file not null");
        }
        else
            Log.e("test","file  null");


    }
    /**
     * 加载本地图片
     * @param url
     * @return
     */
    public static Bitmap getLoacalBitmap(String url) {
        try {
            FileInputStream fis = new FileInputStream(url);
            return BitmapFactory.decodeStream(fis);  ///把流转化为Bitmap图片

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

//    private void initViews()
//    {
//         String path = "file";
//        OutputStream output = null;
//        String SDCard = Environment.getExternalStorageDirectory() + "";
//        imgPath = SDCard + "/" + path + "/" + FileName;//文件存储路径
//        File file = new File(SDCard + "/" + path);
//        if (!file.exists()) {
//            file.mkdir();//创建存储路径
//        }
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                downloadFile(API.LOAD_IMG_URL,imgPath);
//            }
//        }).start();
//    }
}
